package com.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.bean.Config;
import com.bean.HistoryLog;
import com.bean.ParameterBean;
import com.bean.Person;
import com.dao.ConfigDAO;
import com.dao.HistoryLogDAO;
import com.dao.PersonDAO;
import com.servlet.InitServlet;
import com.util.DateHelper;
import com.util.Page;
import com.util.PageUtil;

public class FunctionService {

	/**
	 * 
	 * @param li_op
	 * @param leaseIssue
	 * @param li_unit
	 * @param protocol
	 * @param ip_op
	 * @param ipAddress
	 * @param mac_op
	 * @param macAddress
	 * @param duid_op
	 * @param duid
	 * @param host_op
	 * @param hostName
	 * @param action
	 * @param user_op
	 * @param userName
	 * @param start_op
	 * @param startTime
	 * @param start_unit
	 * @param stop_op
	 * @param stopTime
	 * @param stop_unit
	 * @param mi_op
	 * @param memberIpAddress
	 * @param pageSize
	 * @param orderBy
	 * @param orderSort
	 *            asc or desc
	 * @return
	 */
	public Map<String, Object> findLogs(ParameterBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		int total = historyLogDAO.count(bean);

		String pageSize = bean.getPageSize();
		if (StringUtils.isEmpty(pageSize) || !NumberUtils.isDigits(pageSize)) {
			pageSize = String.valueOf(Page.Page_Size_20);
		}

		String pageNo = bean.getPageNo();
		if (StringUtils.isEmpty(pageNo) || !NumberUtils.isDigits(pageNo)) {
			pageNo = "1";
		}

		Page page = PageUtil.createPage(Integer.valueOf(pageSize), Integer
				.valueOf(pageNo), total);

		List<HistoryLog> list = historyLogDAO.find(bean, page);
		map.put("page", page);
		map.put("list", list);
		return map;
	}

	public Person login(String userName, String password) {
		Person person = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", userName);
		map.put("password", password);
		List<Person> personList = personDAO.findByProperties(map);
		if (personList != null && personList.size() > 0) {
			person = personList.get(0);
		}
		return person;
	}

	public List<Person> findAllPerson() {
		return personDAO.findAll();
	}

	public void mergePerson(Person person) {
		if (person.getId() == 0) {
			person.setId(null);
		}
		personDAO.merge(person);
	}

	public List<Person> deletePerson(Person person) {
		personDAO.delete(person);
		return findAllPerson();
	}

	public List<Config> updateConfigList(List<Config> configList) {
		for (Config config : configList) {
			configDAO.merge(config);
		}
		return findAllConfig();
	}

	public List<Config> findAllConfig() {
		return configDAO.findAll();
	}

	private Map<String, String> getConfigXML() {
		Map<String, String> map = new HashMap<String, String>();
		// xml读取
		File file = new File(InitServlet.WEBAPP_REAL_PATH + "\\xml\\"
				+ "\\config.xml");
		if (file.exists()) {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db;
			try {
				db = dbf.newDocumentBuilder();
				Document doc = db.parse(file);
				Element element = doc.getDocumentElement();
				NodeList nodeList = element.getChildNodes();
				for (int i = 0; i < nodeList.getLength(); i++) {
					Node childNode = nodeList.item(i);
					String key = "";
					String value = "";
					if (childNode instanceof Element) {
						NodeList attributeNodes = childNode.getChildNodes();
						for (int j = 0; j < attributeNodes.getLength(); j++) {
							Node attributeNode = attributeNodes.item(j);
							if (attributeNode instanceof Element) {
								if (key.equals("")) {
									key = attributeNode.getFirstChild()
											.getNodeValue();
								} else {
									value = attributeNode.getFirstChild()
											.getNodeValue();
								}
							}
							if (!key.equals("") && !value.equals("")) {
								map.put(key, value);
							}
						}

					}
				}
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	public String exportExcel(ParameterBean bean) {
		System.out.println(new Date());
		List<Object[]> list = historyLogDAO.find(bean);
		System.out.println(new Date());
		System.out.println(list.size());
		Map<String, String> map = getConfigXML();
		FileOutputStream outSTr = null;
		BufferedOutputStream Buff = null;

		String fileName = DateHelper.formatDateToString(new Date(),
				"yyyyMMddHHmmss")
				+ "log";
		try {
			File file = new File(InitServlet.WEBAPP_REAL_PATH + "\\csv\\");
			if (!file.exists()) {
				file.mkdirs();
			}
			outSTr = new FileOutputStream(new File(InitServlet.WEBAPP_REAL_PATH
					+ "\\csv\\" + fileName + ".csv"));
			Buff = new BufferedOutputStream(outSTr);
			Buff
					.write("Lease Issue,Protocol,IP Address,MAC Address,DUID,Host Name,Action,User Name,Start Time,Stop,Member,Member IP Address\r\n"
							.getBytes("UTF-8"));
			for (Object[] obj : list) {
				Buff.write((DateHelper.formatDateToString((Date) obj[0],
						"yyyy-MM-dd HH:mm:ss")
						+ ","
						+ nullToString(obj[8])
						+ ","
						+ nullToString(obj[2])
						+ ","
						+ nullToString(obj[3])
						+ ","
						+ nullToString(obj[9])
						+ ","
						+ nullToString(obj[4])
						+ ","
						+ nullToString(obj[6])
						+ ","
						+ nullToString(obj[7])
						+ ","
						+ DateHelper.formatDateToString((Date) obj[0],
								"yyyy-MM-dd HH:mm:ss")
						+ ","
						+ DateHelper.formatDateToString((Date) obj[1],
								"yyyy-MM-dd HH:mm:ss")
						+ ","
						+ map.get(obj[5])
						+ "," + obj[5] + "," + "\r\n").getBytes("UTF-8"));
				;
			}
			Buff.flush();
			Buff.close();
			System.out.println(new Date());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				Buff.close();
				outSTr.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return fileName;
	}

	private String nullToString(Object str) {
		if (str == null) {
			return "";
		} else {
			return str.toString();
		}
	}

	public void deleteFile(String fileName) {
		File file = new File(InitServlet.WEBAPP_REAL_PATH + "\\csv\\"
				+ fileName + ".csv");
		if (!file.exists()) {
		} else {
			if (file.isFile()) {
				file.delete();
			}
		}
	}

	private ConfigDAO configDAO;
	private PersonDAO personDAO;
	private HistoryLogDAO historyLogDAO;

	public void setPersonDAO(PersonDAO personDAO) {
		this.personDAO = personDAO;
	}

	public void setConfigDAO(ConfigDAO configDAO) {
		this.configDAO = configDAO;
	}

	public void setHistoryLogDAO(HistoryLogDAO historyLogDAO) {
		this.historyLogDAO = historyLogDAO;
	}

}